/**
 * Copyright ©2012-2018 HopeHaiyang Corporation, All Rights Reserved
 * http://www.wuhanhope.com
 */
package hope.platform.data.server.function.img;

import hope.platform.data.domain.type.FastDFSFile;
import hope.platform.data.load.FdfsClientLoader;
import hope.platform.data.server.function.header.FileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

/**
 * class info
 *
 * @author hujia
 *         Create at 2018/8/9 14:38
 */
@Slf4j
@Service
public class FileServiceImg implements FileService {

    @Autowired
    private FdfsClientLoader client;

    @Override
    public String saveFile(MultipartFile multipartFile) throws IOException {
        String[] fileAbsolutePath = {};
        String fileName = multipartFile.getOriginalFilename();
        String ext = fileName.substring(fileName.lastIndexOf(".") + 1);
        byte[] file_buff = null;
        InputStream inputStream = multipartFile.getInputStream();
        if (inputStream != null) {
            int len1 = inputStream.available();
            file_buff = new byte[len1];
            inputStream.read(file_buff);
        }
        inputStream.close();
        FastDFSFile file = new FastDFSFile();
        file.setName(fileName);
        file.setContent(file_buff);
        file.setExt(ext);
        try {
            fileAbsolutePath = client.uploader(file);  //upload to fastdfs
        } catch (Exception e) {
            log.warn("upload file Exception!", e);
        }
        if (fileAbsolutePath == null) {
            log.warn("upload file failed,please upload again!");
        }
        String path = client.getTrackerUrl() + fileAbsolutePath[0] + "/" + fileAbsolutePath[1];
        return path;
    }

    @Override
    public boolean deleteFile(String fileUrl) {
        String groupName;
        String remoteFileName;
        try {
            int begin = fileUrl.indexOf(client.getTrackerUrl()) + client.getTrackerUrl().length();
            int middle = fileUrl.indexOf('/', begin + 1);
            groupName = fileUrl.substring(begin , middle);
            remoteFileName = fileUrl.substring(middle + 1);
            log.debug("groupName:" + groupName + " remoteFileName:" + remoteFileName);
            client.deleteFile(groupName, remoteFileName);
            return true;
        } catch (Exception e) {
            log.warn("delete failed.");
            return false;
        }
    }
}
